﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApiTest.Dto.Basic;
using WebApiTest.Dto.Utils;
using WebApiTest.Models;

namespace WebApiTest.Service.Basic

{
    public class PersonService
    {
        officeContext db = new officeContext();

        public TableRspDTO list4Table(TableReqDTO tableReqDTO)
        {
            long count = db.Person
                .Where(u => string.IsNullOrEmpty(tableReqDTO.parseQueryParam("name")) || u.Name.Contains(tableReqDTO.parseQueryParam("name")))
                .Where(u => string.IsNullOrEmpty(tableReqDTO.parseQueryParam("deptId")) || u.Name.Contains(tableReqDTO.parseQueryParam("deptId")))
                .LongCount();
            List<JObject> res = db.Person
                .Join(db.Dept, p => p.DeptId, d => d.DeptId, 
                (p, d) => new { key = p.PersonId, personId = p.PersonId, name = p.Name, phone = p.Phone, deptId = d.DeptId, deptName = d.DeptName })
                .Where(u => string.IsNullOrEmpty(tableReqDTO.parseQueryParam("name")) || u.name.Contains(tableReqDTO.parseQueryParam("name")))
                .Where(u => string.IsNullOrEmpty(tableReqDTO.parseQueryParam("deptId")) || u.deptId.ToString().Equals(tableReqDTO.parseQueryParam("deptId")))
                .OrderByDescending(u => u.personId)
                .Skip(tableReqDTO.getStart())
                .Take(tableReqDTO.pageSize)
                .ToList()
                .ConvertAll(r => JObject.FromObject(r));
            PagingDTO pagingDTO = new PagingDTO(
                tableReqDTO.pageNo,
                tableReqDTO.pageSize,
                count,
                res
                );
            return new TableRspDTO(pagingDTO);
        }

        public int add(Person person)
        {
            db.Person.Add(person);
            db.SaveChanges();
            return 1;
        }

        public int update(Person person)
        {
            Person o = db.Person.Find(person.PersonId);
            o.Name = person.Name;
            o.DeptId = person.DeptId;
            o.Phone = person.Phone;
            db.SaveChanges();
            return 1;
        }
        public int remove(string ids)
        {
            List<Person> list = new List<Person>();
            string[] idList = ids.Split(",");
            foreach (string id in idList)
            {
                list.Add(db.Person.Find(long.Parse(id)));
            }
            db.Person.RemoveRange(list);
            //更新到数据库
            db.SaveChanges();
            return list.Count();
        }

        public List<JObject> listAll()
        {
            return db.Person
                .Select(e => new { personId = e.PersonId, name = e.Name })
                .ToList()
                .ConvertAll(e => JObject.FromObject(e));
        }

    }
}
